package com.coffee.admin.utils;

import com.coffee.core.util.DateUtil;
import com.coffee.core.util.MD5Util;
import com.coffee.order.api.utils.MessageUtil;
import org.jasypt.util.text.BasicTextEncryptor;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

public class AESUtil {
    /**
     * 密钥算法
     */
    private static final String ALGORITHM = "AES";
    /**
     * 加解密算法/工作模式/填充方式
     */
    private static final String ALGORITHM_MODE_PADDING = "AES/ECB/PKCS5Padding";

    /**
     * AES加密
     */
    public static String encryptData(String data, String password) throws Exception {
        // 创建密码器
        Cipher cipher = Cipher.getInstance(ALGORITHM_MODE_PADDING);
        SecretKeySpec key = new SecretKeySpec(MD5Util.getMD5Str(password).toLowerCase().getBytes(), ALGORITHM);
        // 初始化
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return Base64Util.encode(cipher.doFinal(data.getBytes()));
    }

    /**
     * AES解密
     */
    public static String decryptData(String base64Data, String password) throws Exception {
        Cipher cipher = Cipher.getInstance(ALGORITHM_MODE_PADDING);
        SecretKeySpec key = new SecretKeySpec(MD5Util.getMD5Str(password).toLowerCase().getBytes(), ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decode = Base64Util.decode(base64Data);
        byte[] doFinal = cipher.doFinal(decode);
        return new String(doFinal, "utf-8");
    }

    public static void parseHexData(String hexData) {

        List<Float>  a= new ArrayList<>();
        List<Integer> b=new ArrayList<>();
        // 去除头部55AA
        String dataWithoutHeader = hexData.startsWith("55AA") ?
                hexData.substring(4) : hexData;

        // 至少需要8字符（4字节）的时间戳
        if (dataWithoutHeader.length() < 8) {
            throw new IllegalArgumentException("数据长度不足");
        }

        // 分离浮点数据和时间戳
        int timestampStart = dataWithoutHeader.length() - 8;
        String floatPart = dataWithoutHeader.substring(0, dataWithoutHeader.length() - 52);
        String intPart = dataWithoutHeader.substring(dataWithoutHeader.length() - 52,dataWithoutHeader.length() - 40);
        String version = dataWithoutHeader.substring(dataWithoutHeader.length() - 40,dataWithoutHeader.length() - 8);
        String timestampHex = dataWithoutHeader.substring(timestampStart);


        // 验证浮点数据长度
        if (floatPart.length() % 8 != 0) {

        }

        for (int i = 0; i < intPart.length(); i+= 2) {
            String group = intPart.substring(i, i + 2);
            int decimal = Integer.parseInt(group, 16);
            b.add(decimal);
        }

        // 解析浮点数
        for (int i = 0; i < floatPart.length(); i += 8) {
            String group = floatPart.substring(i, i + 8);
            System.out.println(i/8+":"+group);
            a.add(hexToFloat(group));
        }
        StringBuilder s = new StringBuilder();
        for (int i = 0; i < version.length(); i += 2) {
            String hexByte = version.substring(i, i + 2);
            int value = Integer.parseInt(hexByte, 16);
            if (value == 0) break; // 遇到空字符终止
            s.append((char) value);
        }
        System.out.println("版本长度："+s.length());
        System.out.println("版本："+s);
        for (int i = 0; i < a.size(); i++) {
            System.out.println(i+":"+a.get(i));
        }
        for (int i = 0; i < b.size(); i++) {
            System.out.println(i+":"+b.get(i));
        }



        // 解析时间戳（无符号int处理）
        int timestamp = hexToInt(timestampHex);
        long millis = timestamp & 0xFFFFFFFFL;

    }

    private static float hexToFloat(String hex) {
        byte[] bytes = hexStringToByteArray(hex);
        ByteBuffer buffer = ByteBuffer.wrap(bytes);
        buffer.order(ByteOrder.LITTLE_ENDIAN);
        return buffer.getFloat();
    }

    private static int hexToInt(String hex) {
        byte[] bytes = hexStringToByteArray(hex);
        ByteBuffer buffer = ByteBuffer.wrap(bytes);
        buffer.order(ByteOrder.LITTLE_ENDIAN);
        return buffer.getInt();
    }

    private static String formatTimestamp(long millis) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(millis * 1000L); // 将秒转换为毫秒
        Date date = calendar.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(date);
    }

    private static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                    + Character.digit(s.charAt(i + 1), 16));
        }
        return data;
    }

    public static void main(String[] args) throws Exception {
//        BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
//        textEncryptor.setPassword("wjyx/service/user/tdHzafwj+kdosdi"); // 设置密码
//
//        String myEncryptedText = textEncryptor.encrypt("Qwer1234"); // 加密数据
//        System.out.println("Encrypted: " + myEncryptedText);
//        String myDecryptedText = "8wtVnti9vWN1JvAXidrsTuToLT5IXw/M"; // 这里应该是加密后的数据
//        String decryptedText = textEncryptor.decrypt(myDecryptedText); // 解密数据
//        System.out.println("decryptedText: " + decryptedText);
        parseHexData("55AA0000AFBD0000FCBB00AC803F00001CBF0000EA3F00007C3FC0789B40069DDFBE5F3EAA426801343CCE604C3D8001403900000000680134BCA1601FBD80014039000000000000000000000000000000000000803F0000000000000000000000000000000000000000000000000000000000000000000000000400008000000000000000000000803F0000803FCDCCCC3DCDCCCC3D0000803F0000A0409A99993E0000A041CDCCCC3E0000803F00000040CDCCCC3D0000803F00000040CDCC4C3FCDCCCC3D0000803F0000A0409A99993E0000A04101000600010076312E302E300000000000000000000038AD0100");
        System.out.println(5925.56*1.08+6512.66*-7.66+5549.76*-12.2+6191.75*-0.03+5554.19*-9.24+5621.09*-2.51+5531.21*-12.15+5533.81*5.71);
        System.out.println(DateUtil.chageTime(1744360800000l));
    }
}
